package com.ojoin.trade.common.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.web.domain.BaseEntity;
import com.ojoin.trade.common.web.domain.Office;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.User;
import com.ojoin.trade.common.web.service.OfficeService;
import com.ojoin.trade.common.web.service.SysManageService;

@Controller
@RequestMapping(value = "sys/office")
public class OfficeController extends SimpleBaseController {

	@Autowired
	private SysManageService sysManageService;

	@Autowired
	private OfficeService officeService;

	@ModelAttribute("office")
	public Office get(@RequestParam(required = false) Integer id) {
		if (null != id) {
			return  officeService.queryById(id);
		} else {
			return  new Office();
		}
	}

	@RequiresPermissions("sys:office:view")
	@ResponseBody
	@RequestMapping(value ="list")
	public Result list(Office office) {
		return new Result(Result.Status.OK, officeService.findList(office));
	}

	@RequiresPermissions("sys:office:view")
	@ResponseBody
	@RequestMapping(value = "form")
	public Result form(Office office) {
		User user = sysManageService.getUser();
		if (office.getParent() == null || office.getParent().getId() == null) {
			office.setParent(user.getOffice());
		}
		office.setParent(officeService.queryById(office.getParent().getId()));
		if (office.getArea() == null) {
			office.setArea(user.getOffice().getArea());
		}
		// 自动获取排序号
		if (null != office.getId() && office.getParent() != null) {
			int size = 0;
			List<Office> list = sysManageService.getOfficeList();
			for (int i = 0; i < list.size(); i++) {
				Office e = list.get(i);
				if (e.getParent() != null
						&& e.getParent().getId() != null
						&& e.getParent().getId()
								.equals(office.getParent().getId())) {
					size++;
				}
			}
			office.setCode(office.getParent().getCode()
					+ StringUtils.leftPad(
							String.valueOf(size > 0 ? size + 1 : 1), 3, "0"));
		}
		return new Result(Result.Status.OK, office);
	}

	@RequiresPermissions("sys:office:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public Result save(Office office) {

		officeService.insertTree(office);

		if (office.getChildDeptList() != null) {
			Office childOffice = null;
			for (String id : office.getChildDeptList()) {
				childOffice = new Office();
				childOffice.setName(sysManageService.getDictLabel(id,
						"sys_office_common", "未知"));
				childOffice.setParent(office);
				childOffice.setArea(office.getArea());
				childOffice.setType("2");
				childOffice.setGrade(String.valueOf(Integer.valueOf(office
						.getGrade()) + 1));
				childOffice.setUseable(Constants.YES);
				officeService.insert(childOffice);
			}
		}

		String id = "0".equals(office.getParentId()) ? "" : office
				.getParentId();
		return new Result(Result.Status.OK, "保存机构'" + office.getName() + "'成功");
	}

	@RequiresPermissions("sys:office:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public Result delete(Office office) {
		office.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
		officeService.delete(office);
		return new Result(Result.Status.OK, "删除机构成功");
	}

	/**
	 * 获取机构JSON数据。
	 * 
	 * @param extId
	 *            排除的ID
	 * @param type
	 *            类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade
	 *            显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public Result treeData(@RequestParam(required = false) Integer extId,
			@RequestParam(required = false) String type,
			@RequestParam(required = false) Long grade,
			@RequestParam(required = false) Boolean isAll,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findList(isAll);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if ((null==extId|| (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
					&& (type == null || (type != null && (type.equals("1") ? type
							.equals(e.getType()) : true)))
					&& (grade == null || (grade != null && Integer.parseInt(e
							.getGrade()) <= grade.intValue()))
					&& Constants.YES.equals(e.getUseable())) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return new Result(Result.Status.OK, mapList);
	}
}
